<template>
  <!--顶部统计、编辑按钮, 未登录时显示去登录的提示-->
  <view v-if="!state.auxiliary.hasLogin">
    <BlankComp />
  </view>
  <view v-else class="cart">
    <view class="top">
      <view class="aggregation">
        <text>全部 {{ state.count }}</text>
      </view>
    </view>
    <!-- 商品条目 -->
    <scroll-view class="main" :style="{ height: cartHeight + 'px' }" scroll-y @scrolltolower="loadMore">
      <view class="list">
        <uni-swipe-action>
          <uni-swipe-action-item
              class="uni-mb-5"
              :right-options="state.swipeConfig.option"
              :show="state.swipeConfig.show[idx]"
              :auto-close="true"
              @click="clickSwipeAction($event, idx)"
              v-for="(product, idx) in state.productList" :key="idx"
          >
            <view class="item">
              <view class="select">
                <checkbox v-if="state.selectedProductList[idx]" :checked="state.selectedProductList[idx].selected" :value="product.id + ''"
                          class="checkbox"
                          @tap="clickCheckbox(idx)"
                ></checkbox>
              </view>
              <view class="image">
                <navigator :url="'/pages/goods/goods?id=' + product.skuId">
                  <image style="width: 80px; height: 100px;" mode="scaleToFill"
                         :src="product.thumbCover"></image>
                </navigator>
              </view>
              <view class="info">
                <view class="summary">
                  <view class="uni-mb-3">
                    <navigator :url="'/pages/goods/goods?id=' + product.skuId">
                      <text class="title">{{ product.title }}</text>
                    </navigator>
                  </view>
                  <view>
                    <text class="spec">{{ product.spec }}</text>
                  </view>
                </view>
                <view class="trade">
                  <text class="price">￥ {{ product.price }}</text>
                  <uni-number-box v-model="product.count" @change="productCountChange($event, idx)"
                                  :step="1"
                                  :min="1"/>
                </view>
              </view>
            </view>
          </uni-swipe-action-item>
        </uni-swipe-action>
        <uni-load-more :status="state.auxiliary.load.status"></uni-load-more>
      </view>
    </scroll-view>

    <!-- 结算 -->
    <view class="bottom" :style="{top: bottomTopPosition + 'px'}">
      <view class="select-all">
        <checkbox :checked="state.allSelected" value="all" @tap="selectAllChange">全部</checkbox>
        <text></text>
      </view>
      <view class="settle-account">
        <text>总计: ￥{{ state.totalPrice }}</text>
        <button @tap="takeBill" type="warn" size="mini">去结算</button>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import {computed, ref} from 'vue'
import type {IProductBriefItem, ProductCheckboxType} from "@/types/product";
import {onShow} from "@dcloudio/uni-app";
import {getShopCarListData, getShopCarStat, removeFromShopCar} from "@/services/shopcar";
import {useUserStore} from "@/stores/user";
import BlankComp from './components/blank.vue'
import {ORDER_PREVIEW_PRODUCTS, ORDER_SOURCE} from "@/constants/storageConstants";
// 获取屏幕边界到安全区域距离
const {windowHeight} = uni.getWindowInfo()
const {hostName} = uni.getSystemInfoSync()
const userStore = useUserStore()

const state = ref({
  productList: [] as Array<IProductBriefItem>,
  selectedProductList: [] as ProductCheckboxType[],
  allSelected: false,
  swipeConfig: {
    show: [
      // "none",
    ] as string[],
    option: [
      {
        text: '收藏',
        style: {
          backgroundColor: '#007aff'
        }
      },
      {
        text: '删除',
        style: {
          backgroundColor: '#F56C6C'
        }
      }
    ]
  },
  totalPrice: 0.0,
  auxiliary: {
    load: {
      status: "more"
    },
    hasLogin: false
  },
  query: {
    page: {
      page: 1,
      size: 10,
      orders: []
    }
  },
  count: 0
})

const bottomTopPosition = computed(() => {
  if (hostName === 'WeChat') {
    // 小程序
    return windowHeight - 42
  } else {
    // 浏览器场景下，tabBar的高度也要加上
    return windowHeight - 42 - 50
  }
})

const cartHeight = computed(() => {
  console.log("@current window height: ", windowHeight, hostName)
  if (hostName === 'WeChat') {
    // 小程序
    return windowHeight
  } else {
    // 浏览器场景下，tabBar的高度也要加上
    return windowHeight - 44 - 40 - 42 - 50
  }
})

const clickSwipeAction = (e: any, idx: number) => {
  console.log("click swipe item: ", e, idx)
  if (e.index === 0) {
    uni.showToast({
      title: "点击了 收藏",
      icon: "none"
    })
    collectAction(idx)
  } else {
    uni.showToast({
      title: "点击了 删除",
      icon: "none"
    })
    delAction(idx)
  }
}

const collectAction = (idx: number) => {
  if (idx >= state.value.productList.length) {
    uni.showToast({
      title: "商品不存在，请稍后再试",
      icon: "none"
    })
    return
  }
  // 匹配具体的商品信息
  console.log("collect product: idx-", idx, 'id: ', state.value.productList[idx].id)
}

const delAction = async (idx: number) => {
  if (idx >= state.value.productList.length) {
    uni.showToast({
      title: "商品不存在，请稍后再试",
      icon: "none"
    })
    return
  }
  await removeFromShopCar(state.value.productList[idx].skuId).then((r) => {
    if (r.code === 0) {
      uni.showToast({
        title: "删除成功",
        icon: "none"
      })
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  }).catch(() => {})
  state.value.productList.splice(idx, 1)
}

const clickCheckbox = (idx: number) => {
  state.value.selectedProductList[idx].selected = !state.value.selectedProductList[idx].selected
  // 判断是否都已被选中
  let allSelected = true
  for (let i = 0; i < state.value.selectedProductList.length; i++) {
    if (!state.value.selectedProductList[i].selected) {
      allSelected = false
    }
  }
  if (allSelected) {
    state.value.allSelected = true
  }
  console.log(state.value.selectedProductList)
  calculateTotalPrice()
}

const productCountChange = (e: any, idx: number) => {
  console.log("number box change: ", e, idx)
}
/**
 * 选择全选按钮
 */
const selectAllChange = () => {
  console.log("点击了全选 ", state.value.allSelected)
  uni.showToast({
    title: "点击了全选",
    icon: "none"
  })
  // 操作所有的购物车选项
  state.value.allSelected = !state.value.allSelected
  if (state.value.allSelected) {
    // 选中
    for (let i = 0; i < state.value.selectedProductList.length; i++) {
      state.value.selectedProductList[i].selected = true
    }
  } else {
    // 取消选择
    for (let i = 0; i < state.value.selectedProductList.length; i++) {
      state.value.selectedProductList[i].selected = false
    }
  }
  calculateTotalPrice()
}
/**
 * 选择商品时计算订单金额
 */
const calculateTotalPrice = () => {
  // 计算服务由后端实现
  console.log("selected product list: ", state.value.selectedProductList)
  let totalPrice = 0
  // 根据已选择的商品id从购物车列表匹配到对应的商品详细数据
  for (let i = 0; i < state.value.selectedProductList.length; i++) {
    const tmpSelectedProduct = state.value.selectedProductList[i]
    if (!tmpSelectedProduct.selected) {
      continue
    }
    const selectedId = tmpSelectedProduct.id
    // 匹配对应的商品详细信息
    const matchedProductList = state.value.productList.filter(tmpProduct => tmpProduct.skuId === selectedId);
    console.log("calculate-matched product: ", matchedProductList)
    if (matchedProductList.length > 0) {
      totalPrice = totalPrice + matchedProductList[0].price * (matchedProductList[0].count as number)
      totalPrice = parseFloat(totalPrice.toFixed(2))
      console.log(
          "calculate-calculate price: ",
          matchedProductList[0].price, matchedProductList[0].count,
          matchedProductList[0].price * (matchedProductList[0].count as number)
      )
    }
  }
  state.value.totalPrice = totalPrice
}
/**
 * 去结算
 * 将要结算的商品数据临时保存到浏览器缓存
 * 订单预览页面读取缓存数据，请求结算接口获取结算数据
 */
const takeBill = () => {
  console.log("@bill price: ", state.value.totalPrice, typeof state.value.totalPrice)
  if (state.value.totalPrice <= 0) {
    uni.showToast({
      title: "请先选择要结算的商品",
      icon: "none"
    })
    return
  }
  const selectedList = state.value.selectedProductList.filter(item => item.selected)
  console.log("@save product info to localstorage,", state.value.totalPrice, selectedList)
  // 从商品列表中过滤出选择的商品数据
  const selectedShopcarProducts = state.value.productList.filter(productItem => {
    for (let i = 0; i < selectedList.length; i++) {
      if (productItem.skuId === selectedList[i].id) {
        return true
      }
    }
    return false
  })
  uni.setStorageSync(ORDER_PREVIEW_PRODUCTS, JSON.stringify(selectedShopcarProducts))
  uni.setStorageSync(ORDER_SOURCE, "SHOP_CAR")
  // 结算 生成预订单、然后确认订单
  // 生成预订单时会返回id，利用id跳转到订单详情页
  uni.navigateTo({
    url: "/pagesOrder/settings/preview"
  })
}
/**
 * 加载首页数据
 */
const loadIndex =async () => {
  initShopCarParams()

  await getShopCarDataAndInitAuxiliary()
}
/**
 * 初始化购物车相关的参数
 */
const initShopCarParams = () => {
  state.value.productList = []
  state.value.selectedProductList = []
  state.value.totalPrice = 0.0
}
/**
 * 查询购物车列表数据并初始化辅助参数
 */
const getShopCarDataAndInitAuxiliary = async () => {
  let rsCount = 0
  state.value.auxiliary.load.status = "loading"
  await getShopCarListData(state.value.query.page).then((r) => {
    rsCount = r.data.list.length
    state.value.productList.push(...r.data.list)
    state.value.auxiliary.load.status = "more"
    if (state.value.query.page.page >= r.data.pages) {
      state.value.auxiliary.load.status = "no-more"
    }
  }).catch(() => {
    state.value.auxiliary.load.status = "no-more"
  })

  for (let i = 0; i < rsCount; i++) {
    // 初始化选择框
    state.value.selectedProductList.push({selected: false, id: state.value.productList[i].skuId})
    // 初始化swipe配置
    state.value.swipeConfig.show.push("none")
  }
}
/**
 * 获取购物车的统计数据
 */
const getShopCarStatData =async () => {
  await getShopCarStat().then((r) => {
    if (r.code === 0) {
      state.value.count = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  })
}
/**
 * 加载购物车下一页数据
 */
const loadMore = () => {
  state.value.query.page.page +=1
  getShopCarDataAndInitAuxiliary()
}

const initData = async () => {
  await getShopCarStatData()
  await loadIndex()
}

onShow(() => {
  if (userStore.isLogin()) {
    state.value.auxiliary.hasLogin = true
    initData()
  } else {
    state.value.auxiliary.hasLogin = false
  }
})
</script>

<style lang="scss">
.cart {
  overflow: auto;

  .top {
    display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: $uni-bg-color;
    padding: 0 10px;
    height: 40px;
  }

  .main {

    .list {
      .item {
        padding: 10px 0;
        background-color: $uni-bg-color;
        margin-bottom: 20px;
        display: flex;
        /*使用scss设置最后一个元素的特殊样式*/
        &:last-child {
          padding: 0 0;
          margin-bottom: 0
        }

        .select {
          display: flex;
          align-items: center;
          padding: 10px;
        }

        .image {
          /*空间不足时该元素不缩放*/
          flex-shrink: 0;
        }

        .info {
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          padding: 0 10px;
          width: 100%;

          .summary {
            .title {
              font-size: $uni-font-size-base;
              display: -webkit-box; /* 必须指定为 box */
              -webkit-box-orient: vertical; /* 设置垂直布局 */
              overflow: hidden;
              text-overflow: ellipsis;
              -webkit-line-clamp: 1; /* 限制为两行 */
            }

            .spec {
              font-size: $uni-font-size-sm;
              color: $uni-color-subtitle;
            }
          }

          .trade {
            display: flex;
            justify-content: space-between;
          }
        }
      }
    }
  }

  .bottom {
    position: fixed;
    left: 0;
    z-index: 999;
    height: 40px;
    width: 100%;
    background-color: $uni-bg-color;
    border-top: 1px solid $uni-border-color;
    border-bottom: 1px solid $uni-border-color;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .select-all {
      width: 20%;
      margin-left: 10px;
    }

    .settle-account {
      width: 70%;
      display: flex;
      justify-content: flex-end;
      align-items: center;
      margin-right: 10px;

      button {
        margin: 0 0 0 5px;
        border-radius: 10px;
      }
    }
  }
}
</style>
